<template>
  <div class="login-container">
    <el-button
      type="primary"
      @click="gotoHome"
      size="mini"
      style="margin-top: 10px; margin-left: 10px"
      >商城首页</el-button
    >
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="isRegister ? registerRules : loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">{{ pageTitle }}</h3>
      </div>
      <!-- <div class="title-container">
        <h3 class="title">{{ formTitle }}</h3>
      </div> -->

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model.trim="loginForm.username"
          placeholder="用户名"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model.trim="loginForm.password"
          :type="passwordType"
          placeholder="密码"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon
            :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
          />
        </span>
      </el-form-item>

      <el-form-item prop="nickname" v-if="isRegister">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="nickname"
          v-model.trim="loginForm.nickname"
          placeholder="姓名"
          name="nickname"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>
      <el-form-item prop="email" v-if="isRegister">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="email"
          v-model.trim="loginForm.email"
          placeholder="邮箱"
          name="email"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>
      <el-form-item prop="phone" v-if="isRegister">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="phone"
          v-model.trim="loginForm.phone"
          placeholder="电话"
          name="phone"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-switch
        v-model="isAdmin"
        active-text="管理员"
        inactive-text="用户"
        inactive-color="#fff"
        style="margin-bottom: 10px; color: #fff"
        :disabled="isRegister"
      >
      </el-switch>
      <el-button
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 30px"
        @click.native.prevent="handleLogin"
        >{{ formTitle }}</el-button
      >
      <div v-if="!isRegister" class="register-tip">
        <span>没有账号？</span>
        <a href="#" @click="changeToRegister">注册</a>
      </div>
      <div v-else class="register-tip">
        <a href="#" @click="changeToLogin">去登录</a>
      </div>
    </el-form>
  </div>
</template>

<script>
import { validUsername, validUsername2 } from "@/utils/validate";
import { resetRouter } from "@/router";
import { register } from "@/api/user";
/**
 * @keyup.enter.native 修饰符
 * @keyup.enter.native 修饰符确保了即使输入框是自定义组件的一部分，也能监听回车事件
 * .native 修饰符确保了即使输入框是自定义组件的一部分，也能监听到其内部原生 input 元素上的键盘回车事件。如果不加 .native，Vue 将仅监听该自定义组件是否在其自定义事件系统中触发了 keyup.enter 事件。由于大多数情况下我们关心的是原生的 DOM 行为，因此在监听键盘事件时常常会带上 .native。
 */
export default {
  name: "Login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername2(value)) {
        callback(new Error("请输入2-10位，以大小写字母数字组成的用户名"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码长度不能小于6位！"));
      } else {
        callback();
      }
    };
    //验证邮箱
    const validateEmail = (rule, value, callback) => {
      const regexp =
        /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
      return regexp.test(value)
        ? callback()
        : callback(new Error("请输入正确的邮箱"));
    };
    //验证手机号
    const validatePhone = (rule, value, callback) => {
      const regexp = /^1[3-9]\d{9}$/;
      return regexp.test(value)
        ? callback()
        : callback(new Error("请输入正确的手机号"));
    };
    return {
      pageTitle: "网上购物商城登录/注册",
      isAdmin: false,
      loginForm: {
        username: "",
        password: "",
        role: 1, //1用户 2 管理员
        nickname: "",
        email: "",
        phone: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      registerRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
        nickname: [{ required: true, trigger: "blur", message: "请输入姓名" }],
        email: [{ required: true, trigger: "blur", validator: validateEmail }],
        phone: [{ required: true, trigger: "blur", validator: validatePhone }],
      },
      loading: false,
      passwordType: "password",
      redirect: undefined,
      isRegister: false,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  mounted() {
    this.autoFocus();
  },
  computed: {
    formTitle() {
      return this.isRegister ? "注册" : "登录";
    },
  },
  methods: {
    gotoHome() {
      this.$router.replace({ path: "/" });
    },
    //自动聚焦光标:1.获取元素dom 2.调用focus()
    //tabindex:tab聚焦的顺序
    autoFocus() {
      this.$refs.username.focus();
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.loginForm.role = this.isAdmin ? 2 : 1;
          if (this.isRegister) {
            //如果是注册
            register(this.loginForm).then((res) => {
              if (res.status === 0) {
                this.$message({
                  message: "注册成功,前往登录",
                  type: "success",
                });
                this.$router.push({ path: "/login" });
                this.$refs.loginForm.resetFields();
                this.isRegister = false;
              } else {
                this.$message({
                  message: "请重新注册！",
                  type: "error",
                });
              }
              this.loading = false;
            });
            return;
          }
          //登录
          if (this.isAdmin) {
            //管理员登录
            this.loginForm.role = 2;
          } else {
            this.loginForm.role = 1;
          }

          this.$store
            .dispatch("user/login", {
              username: this.loginForm.username,
              password: this.loginForm.password,
              role: this.loginForm.role,
            })
            .then(() => {
              // resetRouter(); // 添加这行
              if (this.loginForm.role !== 1) {
                //管理员、管理员登录
                this.$router.push({ path: "/index/index" });
              } else {
                this.$router.push({ path: "/home" });
              }
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          console.log("错误提交！");
          return false;
        }
      });
    },
    changeToRegister() {
      this.isRegister = true;
      //注册，只能注册用户
      this.isAdmin = false;
      this.$refs.loginForm.resetFields();
    },
    changeToLogin() {
      this.isRegister = false;
      this.$refs.loginForm.resetFields();
    },
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
$bg-image: "~@/assets/login/login-bg.png";
.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  background: url($bg-image) no-repeat;
  background-size: 100% 100%;
  overflow: hidden;
  position: relative;
  .login-form {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 520px;
    max-width: 100%;
    padding: 100px 35px 10px;

    overflow: hidden;
    background-color: $bg;
    border-radius: 10px;
    box-shadow: $dark_gray 3px 3px 6px;

    ::v-deep .el-switch {
      .el-switch__label {
        color: #fff;
      }
    }
  }

  .register-tip {
    color: #fff;
    text-align: center;
    a {
      color: rgb(0, 174, 255);
    }
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
      text-shadow: 2px 2px 2px 2px #3a0505;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
